/*
 * Module name : WorkItemForm
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import {
    hideRegion,
    showRegion
} from 'backbone-tools';
import ModalFormBehavior from 'base/behaviors/ModalFormBehavior.js';

import InputWidget from 'widgets/InputWidget.js';
import TextAreaWidget from 'widgets/TextAreaWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import CatalogComponent from 'common/views/CatalogComponent.js';
import RadioChoiceButtonWidget from 'widgets/RadioChoiceButtonWidget';

const template = require('./templates/WorkItemForm.mustache');

const WorkItemForm = Mn.View.extend({
    template: template,
    tagName: 'section',
    id: 'workitem_form',
    behaviors: [ModalFormBehavior],
    partial: false,
    regions: {
        'order': '.field-order',
        quantity_inherited: ".field-quantity_inherited",
        description: '.field-description',
        'mode': '.field-mode',
        supplier_ht: '.field-supplier_ht',
        margin_rate: '.field-margin_rate',
        ht: '.field-ht',
        work_unit_quantity: '.field-work_unit_quantity',
        unity: '.field-unity',
        catalogContainer: "#catalog-container"
    },
    ui: {
        main_tab: "ul.nav-tabs li:first a",
    },
    // Listen to the current's view events
    events: {
        'change': 'updateTotalHt',
    },
    // Listen to child view events
    childViewEvents: {
        'catalog:insert': "onCatalogInsert",
        'quantityMode:change': "onQuantityModeChange",
        'mode:change': 'onModeChange',
    },
    // Bubble up child view events
    childViewTriggers: {
        'change': 'data:modified',
        'finish': 'data:modified',
        'cancel:click': 'cancel:click',
    },
    modelEvents: {
        'change:tva_id': 'refreshTvaProductSelect',
    },
    initialize() {
        this.config = Radio.channel('config');
        this.app = Radio.channel('priceStudyApp');
        this.destCollection = this.getOption('destCollection');
        this.unity_options = this.config.request(
            'get:options',
            'workunits'
        );
    },
    getCommonFieldOptions(attribute, label) {
        let result = {
            field_name: attribute,
            value: this.model.get(attribute),
            label: label,
            editable: true,
        }

        return result;
    },
    refreshForm() {
        this.showDescription();
        this.showModeToggle();
        this.renderModeRelatedFields();
        this.showToggleQuantityButton();
        this.showWorkQuantity();
        this.showUnity();
    },
    renderModeRelatedFields() {
        this.showSupplierHt();
        this.showMarginRate();
        this.showHt();
    },
    showOrder() {
        this.showChildView(
            'order',
            new InputWidget({
                value: this.model.get('order'),
                field_name: 'order',
                type: 'hidden',
            })
        );
    },
    showDescription() {
        let options = this.getCommonFieldOptions('description', "Description");
        options.description = "Description utilisée dans les devis et factures";
        options.tinymce = true;
        options.required = true;
        let view = new TextAreaWidget(options);
        this.showChildView('description', view);
    },
    showModeToggle() {
        this.showChildView(
            "mode",
            new RadioChoiceButtonWidget({
                field_name: "mode",
                className: "form-group",
                label: "Mode de calcul du prix",
                value: this.model.get('mode'),
                "options": [{
                        'label': 'HT',
                        'value': 'ht'
                    },
                    {
                        'label': "Coût d'achat",
                        'value': 'supplier_ht'
                    },
                ],
                finishEventName: 'mode:change',
            })
        )
    },
    showSupplierHt() {
        const region = this.getRegion('supplier_ht');
        if (this.model.get('mode') == 'supplier_ht') {
            let options = this.getCommonFieldOptions('supplier_ht', "Coût unitaire HT");
            options['required'] = true;
            let view = new InputWidget(options);
            this.showChildView('supplier_ht', view);
            showRegion(region);
        } else {
            hideRegion(region);
        }
    },
    showMarginRate() {
        const region = this.getRegion('margin_rate');

        if (this.model.get('mode') == 'supplier_ht') {
            let options = this.getCommonFieldOptions('margin_rate', 'Coefficient de marge');
            options['label'] += " (hérité de l'ouvrage)";
            options['editable'] = false;
            const value = this.destCollection._parent.get('margin_rate') || 0;
            options['value'] = value;
            options.description = "Utilisé pour calculer le 'Prix intermédiaire' depuis le 'Prix de revient' selon la formule 'prix de revient / (1 - Coefficient marge)'";

            let view = new InputWidget(options);
            this.showChildView('margin_rate', view);
            showRegion(region);

        } else {
            hideRegion(region);
        }
    },
    showHt() {
        const region = this.getRegion('ht');

        if (this.model.get('mode') == 'ht') {
            let options = this.getCommonFieldOptions('ht', 'Montant unitaire HT');
            options['required'] = true;

            let view = new InputWidget(options);
            this.showChildView('ht', view);
            showRegion(region);
        } else {
            hideRegion(region);
        }
    },

    showToggleQuantityButton() {
        const value = this.model.get('quantity_inherited') ? 'inherit' : 'custom';
        this.showChildView(
            "quantity_inherited",
            new RadioChoiceButtonWidget({
                field_name: "quantitymode",
                label: "Calcul des quantités",
                value: value,
                "options": [{
                        'label': "Par unité d’œuvre",
                        'value': 'inherit'
                    },
                    {
                        'label': "Indépendamment de l’ouvrage",
                        'value': 'custom'
                    },
                ],
                finishEventName: 'quantityMode:change',
            })
        )
    },
    showWorkQuantity() {
        let label = "Quantité par unité d’œuvre";
        let description_text = "Quantité de ce produit dans chaque unité d’œuvre";

        if (!this.model.get('quantity_inherited')) {
            label = "Quantité";
            description_text = "Quantité indépendante du nombre d’unités d’œuvre de l’ouvrage";
        }

        let options = this.getCommonFieldOptions('work_unit_quantity', label);

        if (description_text != "") {
            options.description = description_text;
        }

        let view = new InputWidget(options);
        this.showChildView('work_unit_quantity', view);
    },
    showUnity() {
        let options = this.getCommonFieldOptions('unity', "Unité");
        options.options = this.unity_options;
        options.placeholder = 'Choisir une unité';
        // options.required = true;

        let view = new SelectWidget(options);
        this.showChildView("unity", view);
    },
    templateContext() {
        let title = "Ajouter un produit"

        if (this.getOption('edit')) {
            title = "Modifier un produit";
        }

        return {
            title: title,
            add: !this.getOption('edit')
        };
    },
    onRender() {
        this.refreshForm();
        if (!this.getOption('edit')) {
            const view = new CatalogComponent({
                query_params: {
                    type_: 'product'
                },
                url: AppOption['catalog_tree_url'],
                multiple: true
            });
            this.showChildView('catalogContainer', view);
        }
    },
    onQuantityModeChange(key, value) {
        this.model.set('quantity_inherited', value == 'inherit');
        this.showWorkQuantity();
    },
    onModeChange(key, value) {
        this.model.set(key, value);
        this.renderModeRelatedFields();
    },
    onAttach() {
        this.getUI('main_tab').tab('show');
    },
    onCatalogInsert(sale_products) {
        let req = this.app.request('insert:from:catalog', this.getOption("destCollection"), sale_products);
        req.then(() => {
            this.app.trigger('product:changed', this.model);
            this.triggerMethod('modal:close');
        });
    },
    onSuccessSync() {
        this.app.trigger('product:changed', this.model);
    }
});
export default WorkItemForm;